/**
 * @file 工单操作-配件报销
 * @author yangjiangming <449654337@qq.com>
 * @date 2018-12-10 20:13:16
 */
layui.define(['layer', 'form', 'table', 'zmnUtils', '$http', 'previewer'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var table = layui.table;
    var opCommonUtils = layui.list_modify_common;
    var NP = layui.NP;
    var $http = layui.$http;
    var previewer = layui.previewer;
    var zmnUtils = layui.zmnUtils;

    /**
     * 保存配置报销 URL
     * @type {string}
     */
    var SAVE_PART_REIMBURSE_URL = '/work/modify/save/part/reimburse.action';

    /**
     * 初始化图片预览器
     * @param selector
     */
    function initImageViewer(selector) {
        previewer.init(selector);
    }

    /**
     * 加载配件表格
     * @param data {array} 配件数据
     */
    function loadTable(data) {
        for (let i = 0; i < Object.keys(data).length; i++) {
            table.init('table-partreimburse-' + i, {
                limit: 50
            });
        }
    }

    /**
     * 判断是否是正整数且最多小数点后两位;
     * @param val {number/string} 字符串或数字
     * @returns {boolean} 返回是否是数字
     */
    function isNumber(val) {
        var reg = /^(\-|\+)?\d+([.]{1}\d{1,2})?$/;//正负整数到小数点后两位
        return reg.test(val);
    }

    /**
     * 获取配件报销数据
     */
    function getPartPriceDataList(index = null) {
        var tableCache = table.cache;
        var partPriceDataList = [];

        if (zmnUtils.isNull(index)) {
            Object.keys(tableCache).forEach(function (key) {
                if (key.startsWith('table-partreimburse')) {
                    partPriceDataList = partPriceDataList.concat(tableCache[key]);
                }
            });
        } else {
            Object.keys(tableCache).forEach(function (key) {
                if (key.startsWith('table-partreimburse-' + index)) {
                    partPriceDataList = partPriceDataList.concat(tableCache[key]);
                }
            });
        }

        return partPriceDataList;
    }

    /**
     * 整理配件报销数据
     * @param partPriceDataList
     * @returns {*}
     */
    function normalizePartPirceData(partPriceDataList) {
        return partPriceDataList.filter(function (item) {
            return zmnUtils.isNumber(+item.price);
        }).map(function (item) {
            return {
                applyId: item.applyId,
                number: item.number,
                orderPartId: item.orderPartId,
                declare: NP.times(item.declare, 100),
                price: NP.times(item.price, 100)
            };
        });
    }

    /**
     * 计算配件报销总额
     */
    function calculateTotalAmount(index) {
        // 计算并设置【某一组】的报销总额
        let partPriceDataList = getPartPriceDataList(index);
        let totalAmount = partPriceDataList.reduce(function (acc, curr) {
            return acc + NP.times(curr.totalAmount, 100);
        }, 0);
        $('#totalAmount-' + index).text(zmnUtils.unit.fenToYuan(totalAmount));

        return totalAmount;
    }

    /**
     * 计算并设置【总申报金额】
     */
    function calculateDeclaredAmount() {
        let reimburseSuccessList = getPartPriceDataList().filter((item) => {
            return $("input[name=status-" + item.applyId + "]:checked").val() == 3
        })
        let declaredAmount = reimburseSuccessList.reduce(function (acc, curr) {
            return acc + NP.times(curr.totalAmount, 100);
        }, 0);
        $('#declaredAmount').text(zmnUtils.unit.fenToYuan(declaredAmount));
    }

    /**
     * 提示消息
     * @param str {string} 提示信息
     * @returns {*}
     */
    function toast(opt) {
        layer.msg(opt.title, {
            icon: opt.icon,
            time: opt.time || 1000,
        }, function () {
            if (opt.icon == 1) {
                opCommonUtils.goOperateHome();
                //    location.reload();
            }
        })
    };

    let tips = function (str) {
        toast({
            title: str,
            icon: 2,
            time: 2000
        });
        return false;
    };

    /**
     * 初始化表单提交事件
     */
    function initSubmit() {
        // 监听表单提交
        form.on('submit(success)', function (data) {

            // 启用重复框
            $("input[type=radio]:disabled").removeAttr("disabled");

            var field = data.field;
            // 需要报销的配件总数
            var reimburseCount = $('#reimburseCount').val();

            var partPriceDataList = getPartPriceDataList();
            var partPricePostDTO = normalizePartPirceData(partPriceDataList);

            if (!partPricePostDTO || partPricePostDTO.length < reimburseCount) {
                zmnUtils.layui.toastError('单价不可为空');
                return false;
            }

            for (let i = 0; i < partPricePostDTO.length; i++) {
                let partPriceData = partPricePostDTO[i];
                if (NP.times(partPriceData.price, partPriceData.number) > partPriceData.declare) {
                    // 启用重复框
                    if ($("input[name=status-" + partPriceData.applyId + "]:checked").val() === '5') {
                        $("input[name=status-" + partPriceData.applyId + "][type=radio]").attr("disabled", "disabled");
                    }
                    tips("报销金额不得大于申报金额");
                    return false;
                }
            }

            let saveReimburseParam = {
                "zsPartReimburseList": [],
                "orderId": field.orderId,
                "workId": field.workId,
                "operatorRemark": field.operatorRemark,
            }

            Object.keys(partsList).forEach((item, index) => {
                let partPriceData = getPartPriceDataList(index);
                let partPriceDataDTO = normalizePartPirceData(partPriceData);
                let partReimburseGroup = {};
                // 报销配件信息
                partReimburseGroup.partPricePostDTO = partPriceDataDTO;
                // 报销单号
                partReimburseGroup.applyId = partPriceData[0].applyId;
                // 报销结果
                partReimburseGroup.status = field['status-' + partReimburseGroup.applyId]


                saveReimburseParam.zsPartReimburseList.push(partReimburseGroup);
            })

            $http.lockSave(SAVE_PART_REIMBURSE_URL, saveReimburseParam, data.elem).then(function () {
                zmnUtils.layui.toastSuccess('操作成功', function () {
                    opCommonUtils.goOperateHome();
                });
            }, (msg) => {
                zmnUtils.layui.toastError(msg);
            });
            return false;
        });
    }

    /**
     * 初始化页面事件
     */
    function initEvent() {
        for (let index = 0; index < Object.keys(partsList).length; index++) {
            let applyId = Object.keys(partsList)[index]

            form.on("radio(status-" + applyId + ")", function (data) {
                calculateDeclaredAmount()
                console.log("status-" + applyId + "，value：", data.value)
            });

            // 监听单价修改事件
            table.on('edit(table-partreimburse-' + index + ')', function (obj) {
                var data = obj.data;
                console.log(data)

                if (!isNumber(data.price)) {
                    tips("请输入正确的金额");
                    data.price = NP.divide(data.declare, data.number);
                    obj.tr.find('td[data-field="price"] input').val(data.price);
                }
                if (NP.times(data.declare, 100) < NP.times(data.price, 100, data.number)) {
                    tips("报销金额不得大于申报金额");
                    data.price = NP.divide(data.declare, data.number);
                    obj.tr.find('td[data-field="price"] input').val(data.price);
                }
                data.totalAmount = zmnUtils.unit.fenToYuan(NP.times(data.price, 100, data.number));
                if (obj.field === 'price') {
                    obj.update(data);
                }

                // 计算【当前组】的配件报销总额
                let totalAmount = calculateTotalAmount(index);
                if (standardReimbursementAmount) {
                    // 检查【当前组】是否存在【不予报销】选项
                    if (totalAmount <= standardReimbursementAmount) {
                        $("#typeContent-" + index).html($("#typeContentTool-2").html());
                    } else {
                        $("#typeContent-" + index).html($("#typeContentTool-1").html());
                    }
                    // 重新给input设置上name
                    $("#typeContent-" + index + " input").attr("name", "status-" + applyId);
                    form.render();
                }
                calculateDeclaredAmount()
            });

        }
    }

    /**
     * 初始化页面
     */
    function initPage() {
        //加载配件表格
        loadTable(partsList);

        // 设置表头
        $('.pass-table').each(function () {
            var that = $(this);
            that.find('.pass-table-title').attr('colspan', that.find('th').length - 1);
        });

        initImageViewer('img');
        calculateDeclaredAmount();
    }

    // 程序入口
    function init() {

        console.log('准备 debug')
        // 初始化页面
        initPage();

        // 初始化事件
        initEvent();

        // 初始化表单提交事件
        initSubmit();
    }

    // 初始化
    init();
    exports('oms_work_modify_partreimburse');
});
